/**
 * pages模版快速生成脚本,执行命令 npm run tep `文件名`
 */
// eslint-disable-next-line strict
const fs = require('fs')

// const rootPath = './src'

let modulePath = null

let centerPath = null

let dirName = null

let unCheck = true

console.log('输入的命令', process.argv)

if (process.argv.includes('check')) {
  unCheck = false
  let idx = process.argv.findIndex(item => item === 'check')
  process.argv.splice(idx, 1)
}

if (process.argv.length === 3) {
  dirName = process.argv[2]
} else if (process.argv.length === 4) {
  modulePath = 'pages-' + process.argv[2] + '/'
  dirName = process.argv[3]
} else if (process.argv.length === 5) {
  modulePath = 'pages-' + process.argv[2] + '/'
  centerPath = process.argv[3] + '/'
  dirName = process.argv[4]
}

let path = `./src/${modulePath ? modulePath : ''}pages/${
  centerPath ? centerPath : ''
}${dirName}`

/**检查模块文件夹是否存在 */

/**检查页面文件夹是否存在 */

if (!dirName) {
  console.log('文件夹名称不能为空！')
  console.log('示例：npm run tep test')
  process.exit(0)
}

// config模版
const configTep = `
export default definePageConfig({
  navigationBarTitleText: '恒蓝云',
})
`

// 页面模版
const indexTep = `
import "./index.scss";
import { View } from "@tarojs/components";
import { observer } from "mobx-react";
import {useContext, useEffect } from "react";
import Taro, { useDidHide, useDidShow,useRouter } from "@tarojs/taro";
import {${dirName}Store} from './model'

const  ${titleCase(dirName)} = () => {
  let router = useRouter()
  const { updatePageQuery,pageQuery,clearPageQuery} =useContext(${dirName}Store)

  // 可以使用所有的 React Hooks
  useEffect(() => {
    console.log("${titleCase(dirName)} useEffect");
  });
  // 对应 onShow
  useDidShow(() => {
    console.log("${titleCase(dirName)} useDidShow");
    updatePageQuery(router.params)
  });
  // 对应 onHide
  useDidHide(() => {
    console.log("${titleCase(dirName)} useDidHide");
    clearPageQuery()
  });
  return <View></View>;
}
export default observer(${titleCase(dirName)});

`

// scss文件模版
const scssTep = `
`

// model文件模版
const modelTep = `
import { observable, computed, action } from 'mobx'
import { createContext } from 'react';
import ChildrenPageUtils from "@/store/extends";

class ${titleCase(dirName)} extends ChildrenPageUtils {
  @observable data: any = null

  @computed get getData() {
    return null
  }

  @action.bound
  handleData() {
  }
}
export const ${dirName}Store = createContext(new ${titleCase(dirName)}())
`
// model文件模版
const compTep = `
import { View } from "@tarojs/components";
export const Comp: React.FC = (): JSX.Element => {
  return (
    <View>
    </View>
  );
};
`

// service页面模版
// const serviceTep = `import Request from '../../utils/request';
//   export const demo = data => Request({
//     url: '路径',
//     method: 'POST',
//     data,
//   });
// `;

makeDir()

/**创建文件 */
async function makeDir() {
  if (unCheck) {
    await checkPath(path)
  }
  console.log('即将写入路径为', path)
  fs.mkdirSync(path) // mkdir $1
  process.chdir(path) // cd $1
  fs.writeFileSync('index.config.ts', configTep)
  fs.writeFileSync('index.tsx', indexTep)
  fs.writeFileSync('index.scss', scssTep)
  fs.writeFileSync('model.ts', modelTep)
  fs.writeFileSync('components.tsx', compTep)
  console.log(`模版${dirName}创建完成`)
  process.exit(0)
}

/**文件名驼峰命名转换 */
function titleCase(str) {
  const array = str.toLowerCase().split(' ')
  for (let i = 0; i < array.length; i++) {
    array[i] =
      array[i][0].toUpperCase() + array[i].substring(1, array[i].length)
  }
  const string = array.join(' ')
  return string
}

/**校验文件路径正确性 */
async function checkPath(p) {
  console.log('开始检验文件路径是否正确:', p)
  let pathSplit = p.split('/')
  for (let i = 2; i < pathSplit.length; i++) {
    const mkdirPath = pathSplit.slice(0, i).join('/')
    let flag = await fsAccess(mkdirPath).catch(err => {})
    if (!flag) {
      console.log('有路径不存在，即将创建:', mkdirPath)
      fs.mkdirSync(mkdirPath) // mkdir $1
    }
  }
}

// eslint-disable-next-line no-shadow
function fsAccess(path) {
  return new Promise((resolve, reject) => {
    fs.access(path, fs.constants.F_OK, err => {
      if (err) {
        console.log(`文件路径不存在:${path}`)
        reject(false)
      } else {
        console.log(`文件路径存在:${path}`)
        resolve(true)
      }
    })
  })
}
